package com.atsmart.app.activity;

import java.io.IOException;
import java.util.List;

import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.adapter.LoadingAdapter;
import com.atsmart.app.adapter.ReportHistoryAdapter;
import com.atsmart.app.exception.BizException;
import com.atsmart.app.model.PageInfo;
import com.atsmart.app.model.ReportHistoryInfo;
import com.atsmart.app.utils.PersistentKeyUtil;
import com.atsmart.app.webservice.ServiceAsynTask;
import com.google.json.JsonParseException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class ReportHistoryActivity extends BaseActivity implements
LoadingAdapter.Delegate, LoadingAdapter.OnLoadingRowShowingHandler, OnClickListener{

	private ListView listView;
	private Button refresh;
	private int historyType;
	private List<ReportHistoryInfo> histories;
	private ReportHistoryAdapter adapter;
	private static final int pageSize = 20;
	private boolean isNeedLoading = false;
	private int totalRow;
	private int pageIndex = 0;
	private static boolean asyntaskIsFinished = true;
	private static final String TAG = ReportHistoryActivity.class.getName();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_list_layout);
		listView = (ListView) findViewById(R.id.listview);
		refresh = (Button) findViewById(R.id.btn_refresh);
		refresh.setOnClickListener(this);
		historyType = getIntent().getIntExtra(PersistentKeyUtil.HISTORY_TYPE, 3);
	}
	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_refresh) {
			if (asyntaskIsFinished) {
				showLoading();
				pageIndex = 0;
				getData();
				asyntaskIsFinished = false;
			}
		} 
	}
	@Override
	protected void onResume() {
		super.onResume();
		if (asyntaskIsFinished) {
			showLoading();
            pageIndex = 0;
            getData();
            asyntaskIsFinished = false;
        }
	}
	private int isPage = 0;
	private void getData() {
		registerLoadStatus(TAG);
		new ServiceAsynTask<List<ReportHistoryInfo>>() {

			@Override
			protected List<ReportHistoryInfo> callService() throws IOException,
					JsonParseException, AssertionError, BizException {
				if(pageIndex == 0){
					isPage = 0;
				}else{
					isPage ++;
				}
				PageInfo pageInfo = new PageInfo();
				pageInfo.begin = pageIndex * pageSize + isPage;
				pageInfo.end = (pageIndex + 1) * pageSize + isPage;
				totalRow = BizApp.getInstance().getSqlHelper().getHistoriesCount(historyType);
				return BizApp.getInstance().getSqlHelper().getHistories(historyType,pageInfo.begin,pageInfo.end);
			}

			@Override
			protected void runWithResult(List<ReportHistoryInfo> result) throws Exception {
				if (result != null && result.size()>0) {
					if (pageIndex == 0) {
						histories = result;
					} else {
						histories.addAll(result);
					}

					bindData();
				}else{
					isEmpty();
				}
				asyntaskIsFinished = true;
				hideLoading();
				finishedLoad(TAG);
			}

			@Override
			protected void runWithError(List<ReportHistoryInfo> result, int iErrorCode)
					throws Exception {
				loadingFailed(TAG, iErrorCode);
				asyntaskIsFinished = true;
//				TaskForAllActivity.hideLoading();
				//hideLoading();
			}
		}.execute();
	}
	private void isEmpty(){
		if (histories == null || histories.size()==0 ) {
			Toast.makeText(this, "你目前还没有汇报过", Toast.LENGTH_SHORT).show();
		}
	}
	private void bindData() {
		if (adapter == null || pageIndex == 0) {
            adapter = new ReportHistoryAdapter(histories);
            adapter.setDelegate(this);
            adapter.setHandler(this);
			listView.setAdapter(adapter);
        } else {
            if (pageIndex >= 1) {
                adapter.appendDataSource(histories);
                adapter.notifyDataSetChanged();
            }
        }
        if (totalRow > (pageIndex + 1) * pageSize) {
            isNeedLoading = true;
        } else {
            isNeedLoading = false;
        }
	}
	@Override
	public void onLoadingRowShowing(LoadingAdapter adapter) {
		if (pageIndex * pageSize < totalRow) {
            if (asyntaskIsFinished) {
                pageIndex++;
                getData();
                asyntaskIsFinished = false;
            }
        }
		
	}

	@Override
	public boolean needLoading() {
		return isNeedLoading;
	}
}
